import BlogService from "@/services/BlogService.js";
export const namespaced = true;

export const state = {
  blogposts: [],
  totalblogs: 0,
  blogpost: {},
  id: 0,
};

export const mutations = {
  ADD_BLOG(state, blogpost) {
    state.blogposts.push(blogpost);
  },
  DELETE_BLOG(state, id) {
    const result = state.blogposts.filter((post) => !post.id === id);
    state.blogposts = result;
  },
  SET_BLOGS(state, blogposts) {
    state.blogposts = blogposts;
  },
  GET_TOTAL(state, number) {
    state.totalblogs = number;
  },
  SET_BLOG(state, blogpost) {
    state.blogpost = blogpost;
  },
  SET_ID(state, id) {
    state.id = id;
  },
};

// context object is what contains every property on vuex store
// you can include state,getters,commit....
// object destucturing to only take commit and dispatch
export const actions = {
  createBlog({ commit }, blogpost) {
    return BlogService.postBlog(blogpost)
      .then((response) => {
        console.log(333, response.data.id);
        commit("SET_ID", response.data.id);
        commit("ADD_BLOG", blogpost);
      })
      .catch((error) => {
        console.log("There was a problem creating your blog: " + error);
      });
  },
  deleteBlog({ commit }, id) {
    return BlogService.deleteBlog(id)
      .then(() => {
        commit("DELETE_BLOG", id);
      })
      .catch((error) => {
        console.log("There was a problem deleting your blog: " + error);
      });
  },
  fetchBlogs({ commit }) {
    return BlogService.getBlogs()
      .then((response) => {
        commit("SET_BLOGS", response.data.blogposts);
        console.log(response.data.blogposts);
      })
      .catch((error) => {
        console.log("There was a problem fetching blogs: " + error);
      });
  },
  fetchBlog({ commit, getters }, id) {
    // const blogpost = getters.getBlogById(id);
    // if (blogpost) {
    //   commit("SET_BLOG", getters.getBlogById(id));
    //   return blogpost;
    // } else {
    return BlogService.getBlog(id).then((response) => {
      commit("SET_BLOG", response.data);
      console.log(response.data);
      return response.data.blogposts[0];
    });
    // }
  },
};

export const getters = {
  getBlogById: (state) => (id) => {
    return state.blogposts.find((blogpost) => blogpost.id === id);
  },
  // 这里state参数返回了一个函数，这个函数再返回一个event
};
